package k2kra;
import java.io.*;
import java.util.*;

//注册账号，保存在本地，查询账号
//暂时没有学习JDBC，不会操作数据库
public class SimpleAccountBase {

    private Map<String, String> base;
    private String file_name;

    //自动读取"base"
    SimpleAccountBase() {
        this.file_name = "base";
        this.base = loadBase();
    }

    SimpleAccountBase(String file_name) {
        this.file_name = file_name;
        this.base = loadBase();
    }

    // 注册账号
    public boolean signUp(String user_name, String password) {
        if (base.putIfAbsent(user_name, password) != null)
            return false;
        return true;
    }

    // 验证账号
    public boolean signIn(String user_name, String password) {
        if (password.equals(base.get(user_name))) {
            return true;
        }
        return false;
    }

    //关闭账号表
    public void close() {
        saveBase();
    }

    // 序列化保存账号表
    private void saveBase() {
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(file_name);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(base);
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取序列化账号表
    private Map<String, String> loadBase() {
        Map<String, String> result = new HashMap<String, String>();
        try {
            FileInputStream fis = new FileInputStream(file_name);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Object obj = ois.readObject();
            result = (HashMap<String, String>)obj;
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //明文显示所有的账号密码
    public String displayAll() {
        return base.toString();
    }

    //测试
    public static void main(String[] args) {
        SimpleAccountBase base = new SimpleAccountBase();

        base.displayAll();

        System.out.println(base.signIn("user_name", "password"));

        base.close();
    }
}